package cn.yunyichina.provider.bed.service.impl;

import cn.yunyichina.provider.bed.vo.PayDepositVoRequest;
import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.base.MedicalCardVo;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by Administrator on 2016/12/14 0014.
 */
@Service
public class PayServiceImpl {

    private Logger logger = LoggerFactory.getLogger(AdmissionNoServiceImpl.class);

    /**
     * 生成押金补缴订单yyt.bed.pay.create
     * @param data
     * @param sessionId
     * @return
     */
    public ResponseObject createPay(String data, String sessionId,String appId) {
        //定义返回结果
        ResponseObject response = new ResponseObject();
        Map<String, Object> result = new HashMap<>();
        //组织信息
        Org org = new Org();
        //订单信息
        OrderExtVo order = new OrderExtVo();
        //订单列表
        List<OrderExtVo> orderList = new ArrayList<>();


        //定义返回码和返回信息
        String resultCode = "0";
        String resultMessage = "执行成功";

        try {
            //获取入参
            logger.info("【出入院-生成押金补缴订单】开始, 请求="+data,",sessionId=" + sessionId);
            PayDepositVoRequest payDepositVoRequest = JsonUtils.parseObject(data, PayDepositVoRequest.class);

            //检查参数合法性
            try {
                Validator.getInstance().validate(payDepositVoRequest);
            } catch (ValidateException ex) {
                logger.info(" 数据校验失败:" + ex.getMessage() + "|入参:" + data + "！");
                logger.error("error", ex);
                response.setResultCodeAndMessage("14002", "数据校验失败:" + ex.getMessage() + "！");
                return response;
            }

            String hospitalCode = payDepositVoRequest.getHospitalCode();
            String branchCode = payDepositVoRequest.getBranchCode();
            String patCardNo = payDepositVoRequest.getPatCardNo();
            Integer patCardType = payDepositVoRequest.getPatCardType();
            String patName = payDepositVoRequest.getPatName();
            String openId = payDepositVoRequest.getOpenId();
            String appCode = payDepositVoRequest.getAppCode();
            Integer payAmount = payDepositVoRequest.getPayAmount();
            String patientId  = payDepositVoRequest.getPatientId();
            String admissionNo = payDepositVoRequest.getAdmissionNo();
            String inTime = payDepositVoRequest.getInTime();
            String deptName = payDepositVoRequest.getDeptName();

//            // 查询患者信息-----------------------------------------------start
//            PatientVo patientvo = new PatientVo();
//            patientvo.setBranchCode(branchCode);
//            patientvo.setHospitalCode(hospitalCode);
//            patientvo.setPatCardNo(patCardNo);
//            patientvo.setPatCardType(String.valueOf(patCardType));
//            patientvo.setSessionId(sessionId);
//            patientvo.setPatName(patName);
//            logger.info("【出入院-生成押金补缴订单-查询患者信息】,getPatient request=" + JSON.toJSONString(patientvo));
//            ResCommon<PatientVoResponse> patientResponse = HisifaceService.getHisifaceClient().getPatient(patientvo);
//            logger.info("【出入院-生成押金补缴订单-查询患者信息】,getPatient response=" + JSONObject.toJSONString(patientResponse));
//            if (!"0".equals(patientResponse.getResultCode())) {
//                response.setResultCodeAndMessage("14011", "查询患者信息失败:" + patientResponse.getResultMessage() + "！");
//                return response;
//            }
//            //获取患者信息
//            patientInfo = JsonUtils.parseObject(patientResponse.getResult(), PatientVoResponse.class);
//            if (StringUtils.isBlank(patientInfo.getPatCardNo())) {
//                response.setResultCodeAndMessage("14011", "查询患者信息失败，无卡号返回！");
//                return response;
//            }
//            logger.info("【出入院-生成押金补缴订单-查询患者信息】,patientInfo=" + JSONObject.toJSONString(patientInfo));
//            // 查询患者信息-----------------------------------------------end

            //查询绑定卡
            MedicalCardVo medicalCard = new MedicalCardVo();
            if(StringUtils.isNotBlank(patCardNo)){

                logger.info("【出入院-生成押金补缴订单-查询绑定卡信息");
                medicalCard =  BaseService.getMedicalCardByCardNo(hospitalCode,patCardNo,patCardType.toString(),appId,openId);
                logger.info("【出入院-生成押金补缴订单-查询绑定卡信息】,response=" + JSONObject.toJSONString(medicalCard));
                if (medicalCard == null) {
                    throw new CallException("14010","找不到绑定卡信息 card_no=" +patCardNo);
                }
            }else{
                logger.info("【出入院-生成押金补缴订单-patCardNo为空，跳过查询绑定卡信息】");
            }

            // 查询组织信息-----------------------------------------------start
            Map<String, String> paramMap = new HashMap<String, String>();

            paramMap.put("org_code", hospitalCode);
            logger.info("【出入院-生成押金补缴订单-查询组织信息】, yyt.base.branchhospital.org.list request=" + JSON.toJSONString(paramMap));
            Response orgResponse = BaseService.callUnderlineFromInternal("yyt.base.branchhospital.org.list", JSON.toJSONString(paramMap));
            logger.info("【出入院-生成押金补缴订单-查询组织信息】, yyt.base.branchhospital.org.list response=" + JSONObject.toJSONString(orgResponse));
            if (!"0".equals(orgResponse.getResultCode())) {
                response.setResultCodeAndMessage("14011", "没有org_code对应的机构信息:" + orgResponse.getResultMessage() + "！");
                return response;
            }
            List<Org> orgList = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
            logger.info("【出入院-生成押金补缴订单-查询组织信息】 orgList ={}",new Object[]{JsonUtils.toJsonString(orgList)});
            if (CollectionUtils.isEmpty(orgList)) {
                response.setResultCodeAndMessage("14011", "不存在[org_code:" + hospitalCode + "]对应的医院信息！");
                return response;
            }
            org = orgList.get(0);
            // 查询组织信息-----------------------------------------------end

            //组装订单
            order.setId(PKGenerator.generateId());
            if("1".equals(payDepositVoRequest.getStatus())){
                //出院结算订单类型
                order.setOrderNo(CacheService.generateOrderNum(OrderExtVo.ORDER_TYPE_OUT_HOSPITAL_SETTLEMENT, 1));
                order.setOrderType(OrderExtVo.ORDER_TYPE_OUT_HOSPITAL_SETTLEMENT);
            }else {
                order.setOrderNo(CacheService.generateOrderNum(OrderExtVo.ORDER_TYPE_IN_HOSPITAL, 1));
                order.setOrderTypeInHospital();
            }
            order.setOpenId(openId);
            order.setOrgCode(hospitalCode);
            order.setBranchCode(branchCode);
            order.setOrgId(org.getId());
            order.setOrgName(org.getOrgName());
            order.setDeptName(deptName);
            order.setOrderStatusCreate();
            order.setPayStatusNotPay();

            order.setPayMode((short) 0);
            order.setUserName(medicalCard.getPatName());
            order.setUserAddress(medicalCard.getPatAddress());
            order.setMedicalCardNo(medicalCard.getMedicalCardNo());
            order.setMedicalCardType(
                    medicalCard.getMedicalCardType() != null ? medicalCard.getMedicalCardType() : (short) 1);
            order.setPayUserId(medicalCard.getPatId());
            order.setIdCardNo(medicalCard.getIdCardNo());
            order.setIdCardType(
                    medicalCard.getIdCardType() != null ? medicalCard.getIdCardType() : (short) 1);
            order.setUserMobile(medicalCard.getPatMobile());
            order.setUserSex(
                    medicalCard.getPatSex() != null ? medicalCard.getPatSex() : (short) 3);
            order.setCreatedTime(DateUtils.dateToString(new Date()));
            order.setPayAmount(payAmount);
            order.setTotalAmount(payAmount);
            order.setAccountAmount(0);
            order.setMedicareAmount(0);
            order.setInsuranceAmount(0);
            Map<String, String> extraParamsMap = new HashMap<String, String>();
            extraParamsMap.put("patient_id", patientId);
            extraParamsMap.put("admission_no", admissionNo);
            extraParamsMap.put("in_time", inTime);
            order.setExtraParams(JsonUtils.toJsonString(extraParamsMap));
            Map<String, String> map = new HashMap<String, String>();
            map.put("org_app_code", appCode);
            logger.info("【出入院-生成押金补缴订单-查询组织应用信息】, yyt.base.orgapp.get request=" + JSON.toJSONString(paramMap));
            Response orgAppResponse = BaseService.callUnderlineFromInternal(sessionId, "yyt.base.orgapp.get", JsonUtils.toJsonString(map));
            logger.info("【出入院-生成押金补缴订单-查询组织应用信息】, yyt.base.orgapp.get response=" + JSONObject.toJSONString(orgAppResponse));
            if("0".equals(orgAppResponse.getResultCode())) {
                JSONObject o = JSONObject.parseObject(orgAppResponse.getResult());
                order.setPlatformId(o.getString("org_id"));
                order.setPlatformName(o.getString("org_name"));
                order.setPlatformOrgAppCode(o.getString("org_app_code"));//平台应用编码
                order.setPlatformCode(o.getString("org_code"));
            }
            order.setPlatformCode(appCode);
            orderList.add(order);

            logger.info("【出入院-生成押金补缴订单-添加订单】,yyt.base.order.out.add request=" + JSON.toJSONString(orderList));
            Response orderResponse = BaseService.callUnderlineFromInternal(sessionId,
                    "yyt.base.order.out.add", JsonUtils.toJsonString(orderList));
            logger.info("【出入院-生成押金补缴订单-添加订单】, yyt.base.order.out.add response=" + JSONObject.toJSONString(orderResponse));
        } catch (Exception e) {
            resultCode = "14999";
            resultMessage = "系统异常:" + e.getMessage();
            e.printStackTrace();
        } finally {
            //组装返回结果
            Map<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("order_no", order.getOrderNo());
            logger.info("【出入院-生成押金补缴订单】 ,查询订单入参=" + JsonUtils.toJsonString(dataMap));
            Response ordResponse = BaseService.callUnderlineFromInternal(sessionId, "yyt.base.order.by.order.no.out.get",
                    JsonUtils.toJsonString(dataMap));
            logger.info("【出入院-生成押金补缴订单】 ,查询订单出参=" + JsonUtils.toJsonString(ordResponse));
            if (!"0".equals(ordResponse.getResultCode())) {
                resultCode = "14013";
                resultMessage = "生成订单失败";
            }

            OrderExtVo orderExtVo = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);

            response.setResultCodeAndMessageAndResult(resultCode, resultMessage, JsonUtils.toJsonString(orderExtVo));
            logger.info("【出入院-生成押金补缴订单】结束, 返回结果=" + JsonUtils.toJsonString(response));
            return response;
        }
    }

    public static void main(String[] args) {
        OrderExtVo order = new OrderExtVo();
        JSONObject o = JSONObject.parseObject("{\"result\":\"[{\"id\":\"ffdbc274acbd11e6990400163e0042e7\",\"org_name\":\"广州市增城区人民医院\",\"org_code\":\"gzszcqrmyy\",\"province_name\":\"广东\",\"city_name\":\"广州\",\"org_type\":1,\"parent_id\":\"0\",\"enable_flag\":1,\"created_time\":\"2017-03-21 18:05:37.0\",\"update_time\":\"2017-03-21 18:05:41.0\"}]\",\"resultCode\":\"0\", \"resultMessage\":\"查询成功!\", \"success\":true}");
        order.setPlatformName(o.getString("org_name"));
        order.setPlatformOrgAppCode(o.getString("org_app_code"));//平台应用编码
        order.setPlatformCode(o.getString("org_code"));

        System.out.println(order.getPlatformCode());
    }
}
